package com.shimmer.CRUD;

import com.shimmer.dao.UserDao;
import com.shimmer.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Package com.shimmer
 * @Author shimmer
 * @Date 2020/8/16 11:38
 * @TODO
 */
public class RetrieveServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 连接数据库，查询users数据
        List<User> users = new UserDao().getUsers();
        // 通过StringBuffer将字符串拼接
        StringBuffer sb = new StringBuffer();
        sb.append("<table align='center' border='1' cellspacing='0'>\r\n");
        sb.append("<tr><td>id</td><td>账户</td><td>密码</td><td>编辑</td><td>删除</td></tr>");
        sb.append("<tr><td colspan='5' align='center'><a href='addUser.html'>添加<a></td></tr>");
        String toFormat = "<tr><td>%d</td><td>%s</td><td>%s</td><td><a href='editUser?id=%d'>编辑</a></td>" +
                "<td><a href='deleteUser?id=%d'>删除</a></td></tr>";
        for (User user : users) {
            String s = String.format(toFormat, user.getId(), user.getName(), 
                    user.getPassword(),user.getId(),user.getId());
            sb.append(s);
        }
        sb.append("</table>");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(sb.toString());
        
    }
}
